package freespiritsocial.io.user.viewmodel

import androidx.lifecycle.viewModelScope
import freespiritsocial.io.user.data.model.bean.ApiRefreshResult
import freespiritsocial.io.user.data.model.bean.PostLocationPojo
import freespiritsocial.io.user.data.model.bean.PostPojo
import freespiritsocial.io.user.data.model.bean.TagPojo
import freespiritsocial.io.user.network.apiService
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request

/**
 * @description explore 依赖得view model
 * @author csw
 * @date 2021-10-17
 */
class ExploreViewModel: BaseViewModel() {
    var tagName: String? = null
        set(value) {
            field = value
            postId = null
            advertisingId = null
            getPostList(true)
        }
    private var postId: Long? = null
    private var advertisingId: Long? = null

    val postResult = MutableSharedFlow<ApiRefreshResult<PostPojo>>(Int.MAX_VALUE)

    fun getPostList(refresh: Boolean = false) {
        if (refresh) {
            postResult.resetReplayCache()
            postId = null
            advertisingId = null
        }
        request({
            apiService.getExploreList(tagName,postId,advertisingId)
        },{
            advertisingId = it.advertisingId
            postId = it.postId
            viewModelScope.launch {
                postResult.emit(ApiRefreshResult(refresh,it.list ?: emptyList(),advertisingId != null || postId != null))
            }
        })
    }

    fun getTagList(callback: (List<TagPojo>) -> Unit) {
        request({
            apiService.getTagList()
        },{
            callback.invoke(it)
        })
    }

    /**
     * 获取所有发布帖子的地区
     */
    fun coordinate(callback: (List<PostLocationPojo>) -> Unit) {
        request({
            apiService.coordinate()
        },{
            it ?: return@request
            callback(it)
        })
    }
}